package com.peakmain.wanandroid.netmodule.net.http;


import com.peakmain.wanandroid.netmodule.net.http.callback.RequestCallBack;
import com.peakmain.wanandroid.netmodule.net.http.params.BaseRequest;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author ：Peakmain
 * version : 1.0
 * createTime：2020/2/22
 * mail:2726449200@qq.com
 * describe：okHttp请求Call
 */
public class RequestCall {
    private BaseRequest okHttpRequest;
    private Request request;
    private Call call;

    public RequestCall(BaseRequest request) {
        this.okHttpRequest = request;
    }

    public Call buildCall(RequestCallBack callback) {
        request = generateRequest(callback);
        call = OkHttpManager.getInstance().getOkHttpClient().newCall(request);
        return call;
    }

    private Request generateRequest(RequestCallBack callback) {
        return okHttpRequest.generateRequest(callback);
    }



    public Call getCall() {
        return call;
    }

    public Request getRequest() {
        return request;
    }

    public BaseRequest getOkHttpRequest() {
        return okHttpRequest;
    }

    /**
     * 同步执行
     * @return
     * @throws IOException
     */
    public Response execute() throws IOException {
        buildCall(null);
        return call.execute();
    }

    /**
     * 异步执行
     * @param callback
     * @param <T>
     */
    public <T> void execute(RequestCallBack<T> callback) {
        buildCall(callback);
        if (callback != null) {
            callback.onBefore(getOkHttpRequest().getId());
        }
        OkHttpManager.getInstance().execute(this, callback);
    }

    /**
     * 取消请求
     */
    public void cancel() {
        if (call != null) {
            call.cancel();
        }
    }


}
